import React from 'react';
import { Input,Grid,Icon,Item,Button,Dimmer,Loader } from 'semantic-ui-react'
import 'semantic-ui-css/semantic.min.css'
import ImageGallery from 'react-image-gallery'; 
import "react-image-gallery/styles/css/image-gallery.css";
import './home.css';
import axios from 'axios';
import Calculate from './calculate';
import Map from './map';
import {withRouter} from "react-router-dom"; // 需要进行编程式路由导航的引入withRouter把组件传入该方法（home和list都是在main中的路由下）

class Home extends React.Component {
  constructor(props){
    super(props)
    this.state={
      images:[],
      menus:[],
      infos:[],
      faqs:[],
      houses:[],
      loading:true,
      showCalc:false,
      showMap:false
    }
  }
  doRequest(path){
    return axios.post(path).then(result=>{
      if(result.meta.status === 200) {
        // axios调用本身返回的就是一个promisee对象 在then中直接返回数据，那么该数据会提供给下一个then
        return result.data.list;
      }
    })
    // 方法2
    // return new Promise((resolve,reject)=>{
    //   axios.post(path).then(result=>{
    //       if(result.meta.status === 200) {
    //         // 在then中直接返回数据，那么该数据会提供给下一个then
    //         resolve(result.data.list)
    //       }
    //     })
    // })
  }
  // toggleCalc=()=>{
  //   this.setState({
  //     showCalc: !this.state.showCalc
  //   })
  // }
  componentDidMount(){
    let images = this.doRequest('homes/swipe');
    let menus = this.doRequest('homes/menu');
    let infos = this.doRequest('homes/info');
    let faqs = this.doRequest('homes/faq');
    let houses = this.doRequest('homes/house');
    Promise.all([images,menus,infos,faqs,houses]).then((result)=>{
      this.setState({
        images: result[0],
        menus: result[1].filter(it=>it.menu_name!=='计算器'),
        infos: result[2],
        faqs: result[3],
        houses: result[4],
        loading: false // 所有的接口调用结果都拿到才进行设置
      });
    });
  }
  toggleMenu = (name)=>{
    switch(name){
      case '二手房':
        this.props.history.push('/home/list',{query:{menuName:name,homeType:1}});
        break;
      case '新房':
        this.props.history.push('/home/list',{query:{menuName:name,homeType:2}});
        break;
      case '租房':
        this.props.history.push('/home/list',{query:{menuName:name,homeType:3}});
        break;
      case '海外':
        this.props.history.push('/home/list',{query:{menuName:name,homeType:4}});
        break;
      case '地图找房':
        this.setState({
          showMap: !this.state.showMap
        });
        break;
      case '查公交':
        
        break;
      case '计算器':
      this.setState({
        showCalc: !this.state.showCalc
      })
        break;
      case '问答':
        
        break;
      default:
        console.log('没有匹配操作')
  }
  }
  render() {
    const Menu=(props)=>{
      const list=props.menuData.map((item)=>{ //map循环返回的数组中是被react包装好的对象,这个数组放到标签内就会自动填充（类似于传参）
        return (
          <Grid.Column onClick={this.toggleMenu.bind(this,item.menu_name)} key={item.id}>
             <div className='home-menu-item'>
              <Icon name='home' size='big' />
             </div>
             <div>{item.menu_name}</div>
          </Grid.Column>
        )
      })
      return(
      <Grid divided padded >
        <Grid.Row columns={4}>
          {list}
        </Grid.Row>
      </Grid>
      )
    }
    const Info=(props)=>{
      const info=props.InfoData.map((item)=>{
        return (
        <Item.Header key={item.id}>
          <span>限购 ●</span>
          <span>{item.info_title}</span>
        </Item.Header>
        )
      })
      return(
        <div className='home-msg'>
        <Item.Group unstackable>
          <Item className='home-msg-img' >
            <Item.Image size='tiny' src={'http://127.0.0.1:8086/public/zixun.png'} />
            <Item.Content verticalAlign='top'>
              {info}
              <div className="home-msg-more">
                <Icon name='angle right' size='big' />
              </div>
            </Item.Content>
          </Item>
        </Item.Group>
      </div>
      )
    }
    const Faq=(props)=>{
      const faq=props.faqData.map((item)=>{
        return (
          <li key={item.question_id}>
          <div  >
            <Icon name='question circle outline' />
            <span>{item.question_name}</span>
          </div>
          <div>
            {
              item.question_tag.split(',').map((tag,index)=>{
                return <Button key={index} basic color='green' size='mini'>{tag}</Button>
              })
            }
            <div>{item.atime} ● <Icon name='comment alternate outline' /> {item.qnum}</div>
          </div>
        </li>
        )
      })
      return(
      <div className='home-ask'>
        <div className='home-ask-title'>好客问答</div>
        <ul>
          {faq}
        </ul>
      </div>
      )
    }
    const House = (props) => {
      let newHouse = [];
      let oldHouse = [];
      let hireHouse = [];
      props.houseData.forEach((item,index)=>{
        let tags = item.home_tags.split(',').map((tag,index)=>{
          return <Button key={index} basic color='green' size='mini'>{tag}</Button>
        })
        let houseItem = (
          <Item key={item.id}>
            <Item.Image src={'http://127.0.0.1:8086/public/home.png'}/>
            <Item.Content>
              <Item.Header>{item.home_name}</Item.Header>
              <Item.Meta>
                <span className='cinema'>{item.home_desc}</span>
              </Item.Meta>
              <Item.Description>
                {tags}
              </Item.Description>
              <Item.Description>{item.home_price}</Item.Description>
            </Item.Content>
          </Item>
        );
        if(index < 2) {
          newHouse.push(houseItem);
        }else if(index === 2 || index === 3) {
          oldHouse.push(houseItem);
        }else{
          hireHouse.push(houseItem);
        }
      })
      return (
        <div>
          <div>
            <div className='home-hire-title'>最新开盘</div>
            <Item.Group divided unstackable>
              {newHouse}
            </Item.Group>
          </div>
          <div>
            <div className='home-hire-title'>二手精选</div>
            <Item.Group divided unstackable>
              {oldHouse}
            </Item.Group>
          </div>
          <div>
            <div className='home-hire-title'>组一个家</div>
            <Item.Group divided unstackable>
              {hireHouse}
            </Item.Group>
          </div>
        </div>
      );
    }
    return (
      <div className='home-container'>
        {this.state.showCalc && <Calculate hideCalc={this.toggleMenu.bind(this,'计算器')}/>}
        {this.state.showMap && <Map hideMap={this.toggleMenu.bind(this,'地图找房')}/>}
      <div className="home-topbar">
        <Input fluid icon={{ name: 'search', circular: true, link: true }} placeholder='搜房源...' />
      </div>
      <Dimmer inverted active={this.state.loading} page>
          <Loader>Loading</Loader>
        </Dimmer>
      <div className="home-content">
      <ImageGallery items={this.state.images} showThumbnails={false} />
      <Menu menuData={this.state.menus}/>
      <Info InfoData={this.state.infos}/>
      <Faq faqData={this.state.faqs}/>
      <House houseData={this.state.houses}/>
      </div>
    </div>
    );
  }
}
export default withRouter(Home);
